<template>
  <van-popup v-model:show="state.show" class="popup-box" style="height: 100%" position="right">
    <div class="page">
      <global-header :title="title" @back="closed"> </global-header>
      <main class="page-main">
        <van-field
          v-model="state!.Name"
          label="用户名"
          placeholder="请输入6-15位字母数字组合用户名"
          input-align="right"
          :disabled="isEdit"
        ></van-field>
        <van-field
          v-model="state!.Password"
          label="密码"
          placeholder="请输入6-16位字母数字组合的密码"
          input-align="right"
        ></van-field>
        <van-field
          v-model="state!.Remark"
          label="备注"
          placeholder="请输入备注"
          input-align="right"
        ></van-field>
        <van-field
          v-model="state.StatusText"
          label="状态"
          placeholder="请选择状态"
          is-link
          readonly
          input-align="right"
          @click="statusShow = true"
        />
        <van-field
          v-model="state.editCheckedText"
          label="编辑"
          placeholder="请选择编辑"
          is-link
          readonly
          input-align="right"
          @click="openEditCheck"
        />
        <van-field
          v-model="state.applyText"
          label="申请"
          placeholder="请选择申请"
          is-link
          readonly
          input-align="right"
          @click="openApply"
        />
        <van-field
          v-model="state.menuText"
          label="菜单"
          placeholder="请选择菜单"
          is-link
          readonly
          input-align="right"
          @click="openMenu"
        />
      </main>

      <div class="p-[15px] bg-[#FFFFFF]">
        <div class="flex gap-[10px]">
          <van-button
            @click="update"
            class="!flex-1 !bg-[#3976CC] !text-[#FFFFFF] rounded-[5px]"
            block
          >
            保存
          </van-button>
        </div>
      </div>
    </div>
  </van-popup>

  <van-popup v-model:show="statusShow" destroy-on-close round position="bottom">
    <van-picker
      :v-model="state.StatusText"
      :columns="statusList"
      @cancel="statusShow = false"
      @confirm="onStatusConfirm"
    />
  </van-popup>
  <SubPopupMultiple
    ref="subPopupMultipleEditCheckRef"
    title="选择状态"
    :itemList="editCheckedList"
    @update="item => updateItem(item, 'editCheckedText')"
  />
  <SubPopupMultiple
    ref="subPopupMultipleApplykRef"
    title="选择申请"
    :itemList="applyList"
    @update="item => updateItem(item, 'applyText')"
  />
  <SubPopupMultiple
    ref="subPopupMultipleMenuRef"
    title="选择菜单"
    :itemList="menuList"
    @update="item => updateItem(item, 'menuText')"
  />
</template>

<script lang="ts" setup>
import { debounce } from "lodash-es";
import { reqUserSubAccountsEdit, reqUserSubAccountsAdd } from "@/api/user";
import { showSuccessToast } from "vant";
import SubPopupMultiple from "./sub-popup-multiple.vue";

const props = withDefaults(
  defineProps<{
    uid: number | null;
    listData: Object;
    item: any;
  }>(),
  {}
);
const emit = defineEmits<{
  (event: "update"): void;
}>();

const state = reactive({
  show: false,
  Name: "",
  Password: "",
  Remark: "",
  Status: "1",
  StatusText: "是",
  editChecked: "",
  editCheckedText: "",
  menu: "",
  menuText: "",
  apply: "",
  applyText: ""
});
const subPopupMultipleEditCheckRef = ref();
const subPopupMultipleApplykRef = ref();
const subPopupMultipleMenuRef = ref();
const statusShow = ref(false);
const statusList = [
  { text: "是", value: "1" },
  { text: "否", value: "0" }
];
const editCheckedList = ref([]);
const applyList = ref([]);
const menuList = ref([]);
const isEdit = ref(false);

const title = computed(() => {
  return isEdit.value ? "编辑子账号" : "新增子账号";
});

watch(
  () => props.listData,
  (value: any) => {
    editCheckedList.value = value?.editPerms || [];
    applyList.value = value?.applyPerms || [];
    menuList.value = value?.menuPerms || [];
  },
  {
    immediate: true,
    deep: true
  }
);
// 初始化数据
const initializeState = () => {
  if (props.item) {
    state.Name = props.item.Name || "";
    state.Password = "";
    state.Remark = props.item.Remark || "";
    state.Status = props.item!.IsUsed || "0";
    state.StatusText = state.Status == "0" ? "否" : "是";
    menuList.value.forEach((item: any) => {
      if (props.item!.Perms.includes(item.Id)) {
        item.selected = true;
      }
    });
    applyList.value.forEach((item: any) => {
      if (props.item!.Perms.includes(item.Id)) {
        item.selected = true;
      }
    });
    editCheckedList.value.forEach((item: any) => {
      if (props.item!.Perms.includes(item.Id)) {
        item.selected = true;
      }
    });
  }
};

const update = debounce(
  async () => {
    if (!state.Name) {
      return showToast("请输入用户名");
    }
    if (!state.Password && !isEdit.value) {
      return showToast("请输入密码");
    }
    try {
      if (!isEdit.value) {
        await reqUserSubAccountsAdd({
          Name: state.Name,
          Password: state.Password,
          Remark: state.Remark,
          IsUsed: Number(state.Status),
          Perms: [...state.editChecked, ...state.menu, ...state.apply]
        });
      } else {
        if (!props.uid) {
          return showToast("非法操作");
        }
        await reqUserSubAccountsEdit({
          Id: props.uid,
          Name: state.Name,
          ...(state.Password ? { Password: state.Password } : {}),
          Remark: state.Remark,
          IsUsed: Number(state.Status),
          Perms: [...state.editChecked, ...state.menu, ...state.apply]
        });
      }
      emit("update");
      showSuccessToast(isEdit.value ? "修改成功" : "新增成功");
    } catch (error) {
      console.log(error);
    }
  },
  500,
  { leading: true, trailing: false }
);

const onStatusConfirm = (value: any) => {
  state.StatusText = value.selectedOptions[0].text;
  state.Status = value.selectedOptions[0].value;
  statusShow.value = false;
};

const closed = () => {
  state.show = false;
  state.Name = "";
  state.Password = "";
  state.Remark = "";
  state.Status = "1";
  state.StatusText = "是";
  state.editChecked = "";
  state.editCheckedText = "";
  state.menu = "";
  state.menuText = "";
  state.apply = "";
  state.applyText = "";
  menuList.value.forEach((item: any) => {
    item.selected = false;
  });
  applyList.value.forEach((item: any) => {
    item.selected = false;
  });
  editCheckedList.value.forEach((item: any) => {
    item.selected = false;
  });
};

const open = (edit = false) => {
  isEdit.value = edit;
  state.show = true;
  if (edit) {
    initializeState();
  }
};

const openEditCheck = () => {
  subPopupMultipleEditCheckRef.value?.open();
};
const openMenu = () => {
  subPopupMultipleMenuRef.value?.open();
};
const openApply = () => {
  subPopupMultipleApplykRef.value?.open();
};

const updateItem = (item: any, type: "editCheckedText" | "menuText" | "applyText") => {
  state[type] = item.map((dataItem: any) => dataItem.text).join(",");
  if (type == "editCheckedText") {
    state.editChecked = item.map((dataItem: any) => dataItem.value);
  } else if (type == "menuText") {
    state.menu = item.map((dataItem: any) => dataItem.value);
  } else if (type == "applyText") {
    state.apply = item.map((dataItem: any) => dataItem.value);
  }
};

defineExpose({
  closed,
  open
});
</script>
